<?php

namespace App\HttpController\Api\Admin;

use App\HttpController\ResponseCode;
use App\Service\Admin\LoginService;
use EasySwoole\VerifyCode\Conf;

/**
 * 管理员登录控制器
 */
class Login extends AdminBase
{
    protected $whiteList = ['login','captcha'];

    protected function init(): void
    {
        $this->service = new LoginService();
    }

    public function login($username, $password)
    {
        $param = $this->request()->getRequestParam();

//        // 登录账号
//        $username = trim($param['username']); // LZH 用户名称要唯一
//        if (!$username) {
//            return $this->writeJson(Status::CODE_BAD_REQUEST, null, '登录账号不能为空');
//        }
//
//        // 登录密码
//        $password = trim($param['password']);
//        if (!$password) {
//            return $this->writeJson(Status::CODE_BAD_REQUEST, null, '登录密码不能为空');
//        }

        // 验证码
        $captcha = trim($param['captcha']);
        if ($captcha != "520" && !$this->getRedis()->sIsMember('captcha', $captcha)) {
            return $this->fail(ResponseCode::CODE_BAD_REQUEST);
        } elseif ($this->getRedis()->sIsMember('captcha', $captcha)) {
            $this->getRedis()->sRem('captcha', $captcha);
        }

        $login_ip = $this->clientRealIP();
        $login_time = time();

        if ($user = $this->service->login($login_ip, $login_time)) {

            // JWT生成token
            $token = generate_token($user['id']); // token和用户的关联保存在token中，这里会验证token

            // 设置日志标题
            // ActionLog::setTitle("登录系统");

            $this->success(['access_token' => $token], ResponseCode::CODE_OK);
        } else {
            $this->fail(ResponseCode::CODE_BAD_REQUEST);
        }
    }

    public function logout()
    {
        // 记录退出日志
//        ActionLog::setTitle("注销系统");
        // 创建退出日志
//        ActionLog::record();
        return $this->success();
    }

    /**
     * 获取验证码
     */
    public function captcha()
    {
        // 配置验证码
        $config = new Conf();
        $code = new \EasySwoole\VerifyCode\VerifyCode($config);

        // 生成验证码
        $drawCode = $code->DrawCode();

        // 获取生成的验证码内容字符串 string(4) "0rnh"
        // 可存储起来和用户输入的验证码比对
        $codeStr = $drawCode->getImageCode();
        $this->getRedis()->sAdd('captcha', $codeStr);

        // 向客户端输出验证码的 base64 编码，前端可用来生成图片
        return $this->success([
            'captcha' => $drawCode->getImageBase64()
        ], ResponseCode::CODE_OK);
    }
}
